<template>
    <el-container class="upload-page">
      <el-main>
        <!-- <div>
          <el-input type="file" ref="uploadRef" @change="upload" multiple class="uploadinput"/>
        </div> -->
        <el-button :class="el-input-login" type="primary" @click="triggerUpload" style="width: 100%;">文件上传</el-button>
        <input type="file" ref="fileTemp" multiple class="up-load-file-btn" @change="upload" v-show="false"/>
        <div v-for="item in reversedItems" :key="item.key" :currentProcess="item.currentProcess" class="process">
          <el-slider
            class="custom-slider"
            v-model="item.currentProcess"
            :max="100"
            disabled
          ></el-slider>
            <div class="upload-text">{{item.name}}-{{item.currentProcess}}%-
              <i class="el-icon-video-play" @click="changeStauts(item.key)" v-if="!item.status" style="font-size:18px;color: white;"></i>
              <i class="el-icon-video-pause" @click="changeStauts(item.key)" v-else style="font-size:18px;color: white;"></i>
              <!-- <i class="el-icon-delete" style="font-size:15px;color: red;"></i> -->
            </div>
        </div>
      </el-main>
    </el-container>
</template>

<script>
//import { reactive } from "vue";
import axios from "axios";
import SparkMD5 from 'spark-md5';

export default({
name: 'UpLoadfiles',
// Add your component options here

data() {
    return {
      fileList: [],
      fileSize: 10 * 1024 * 1024, // 1M
  }
},

computed: {
    // 使用计算属性来返回倒序后的数组
    reversedItems() {
      return this.fileList.slice().reverse();
    }
  },
// Add your methods  here
methods: {

  upload() {
    let files = event.target.files;
    for (let i = 0; i < files.length; i++) {
      console.log(files[i].name)
      //this.fileList.unshift({
      this.fileList.push({
        total: 0,
        status: true,
        name: files[i].name,
        requestFn: [],
        key: null,
        hashList: [],
        currentProcess: 0
      })
      this.setFileBuffer(files[i]);
  }
},

setFileBuffer(file) {
  const reader = new FileReader();
  //处理load事件。该事件在读取操作完成时触发
  const keyIndex = this.fileList.findIndex((item) => item.name == file.name);
  reader.onload = async () => {
    //let key = "test"
    let key = await this.setChunkHash(reader.result);
    this.fileList[keyIndex].key = key
    // this.fileList.push({
    //   total: 0,
    //   status: true,
    //   name: file.name,
    //   requestFn: [],
    //   key: key,
    //   hashList: [],
    //   currentProcess: 0
    // });
    console.log(this.fileList)
    // this.setChunk(reader.result, 0, key);
    this.setChunkV2(reader.result, 0, key);
  };
  reader.readAsArrayBuffer(file);
},

//为每个切片封装ajax请求
// setChunk(fileBuffer, i = 0, key) {
//   let index = i + this.fileSize;
//   let isEnd = false;
//   if (index > fileBuffer.byteLength) {
//     index = fileBuffer.byteLength;
//     isEnd = true;
//   }
//   // 根据key,获取当前文件处于fileList中的下标
//   const keyIndex = this.fileList.findIndex((item) => item.key == key);
//   // 封装每个切片
//   this.fileList[keyIndex].requestFn.push(() => {
//     return new Promise(async (reslove, reject) => {    /* eslint-disable no-async-promise-executor */
//       let formData = new FormData();
//       let content = fileBuffer.slice(i, index);
//       formData.append("file", this.arrayBufferToBlob(content));
//       formData.append("key", key);
//       const chunkHash = await this.setChunkHash(fileBuffer.slice(i, index));
//       formData.append("hash", chunkHash);
//       this.fileList[keyIndex].hashList.push(chunkHash);
//       formData.append("file_size", index - i);
//       await this.apiUploadFile(formData); // apiUploadFile 为上传接口
//       this.fileList[keyIndex].requestFn.splice(0, 1);
//       this.fileList[keyIndex].currentProcess = parseInt(((1 - this.fileList[keyIndex].requestFn.length / this.fileList[keyIndex].total)*100).toFixed(0));
//       let a = true
//       if(a){
//         reslove(true);
//       }
//       else{
//         reject(false);
//       }
//     });
//   });
//   // 判断当前文件的切片是否已经全部封装
//   if (isEnd) {
//     this.fileList[keyIndex].total = this.fileList[keyIndex].requestFn.length;
//     this.startUpload(key);
//     console.log(this.fileList)
//     return;
//   } else {
//     this.setChunk(fileBuffer, index, key);
//     console.log(this.fileList)
//   }
// },


//为每个切片封装ajax请求
setChunkV2(fileBuffer, i = 0, key) {
  let index = i + this.fileSize;
  let isEnd = false;
  if (index > fileBuffer.byteLength) {
    index = fileBuffer.byteLength;
    isEnd = true;
  }
  // 根据key,获取当前文件处于fileList中的下标
  const keyIndex = this.fileList.findIndex((item) => item.key == key);
  // 封装每个切片
  this.fileList[keyIndex].requestFn.push({
      i: i,
      index: index,
      key: key,
      keyIndex: keyIndex,
      fileBuffer: fileBuffer
  });
  // 判断当前文件的切片是否已经全部封装
  if (isEnd) {
    this.fileList[keyIndex].total = this.fileList[keyIndex].requestFn.length;
    this.startUpload(key);
    console.log(this.fileList)
    return;
  } else {
    // this.setChunk(fileBuffer, index, key);
    this.setChunkV2(fileBuffer, index, key);
    console.log(this.fileList)
  }
},

async setChunkV2Detaile(requestFn){
  let formData = new FormData();
  let content = requestFn.fileBuffer.slice(requestFn.i, requestFn.index);
  formData.append("file", this.arrayBufferToBlob(content));
  formData.append("key", requestFn.key);
  const chunkHash = await this.setChunkHash(requestFn.fileBuffer.slice(requestFn.i, requestFn.index));
  formData.append("hash", chunkHash);
  this.fileList[requestFn.keyIndex].hashList.push(chunkHash);
  formData.append("file_size", requestFn.index - requestFn.i);
  var cecusername = sessionStorage.getItem('user_uuid')
  formData.append("cecusername", cecusername);
  await this.apiUploadFile(formData); // apiUploadFile 为上传接口
  this.fileList[requestFn.keyIndex].requestFn.splice(0, 1);
  this.fileList[requestFn.keyIndex].currentProcess = parseInt(((1 - this.fileList[requestFn.keyIndex].requestFn.length / this.fileList[requestFn.keyIndex].total)*100).toFixed(0));
},

arrayBufferToBlob(arrayBuffer) {
  return new Blob([arrayBuffer]);
},

// 开始上传(步骤3)
async startUpload(key) {
  const keyIndex = this.fileList.findIndex((item) => item.key == key);
  //await this.fileList[keyIndex].requestFn[0]();
  await this.setChunkV2Detaile(this.fileList[keyIndex].requestFn[0])
  if (this.fileList[keyIndex].requestFn.length > 0) {
    if (this.fileList[keyIndex].status) {
      this.startUpload(key);
    }
  } else {
    // 上传完毕,请求合并文件
    console.log("上传完毕,请求合并文件")
    const { data } = await this.mergeFile({
      chunkFiles: this.fileList[keyIndex].hashList,
      key: key,
      fileName: this.fileList[keyIndex].name,
      cecip:  sessionStorage.getItem('cecip'),
      cecusername: sessionStorage.getItem('user_uuid')
    });
    console.log(data)
    this.fileList[keyIndex].key = null;
    this.fileList[keyIndex].name += "-完成"; 
  }
},

mergeFile(formData) {
  return new Promise((reslove, reject) => {  /* eslint-disable no-async-promise-executor */
    console.log(formData)
    axios
      .post("/api/chunkuploadmerge", formData, {
        headers: {
          "Content-Type": "application/json",
        },
      })
      .then((result) => {
        console.log(result)
        reslove(true);
      })
      .catch((err) => {
        reject(false);
        console.log(err)
      });
  });
},

// 计算hash值
setChunkHash(chunk) {
  return new Promise((reslove) => {
    const spark = new SparkMD5.ArrayBuffer();
    spark.append(chunk);
    reslove(spark.end());
  });
},

// 上传
apiUploadFile(formData) {
  return new Promise((reslove) => {
    axios.post("/api/chunkupload", formData, {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      })
      .then((result) => {
        console.log(result)
        reslove(true);
      })
      .catch((err) => {
        console.log(err)
      });
  });
},

triggerUpload () {
  this.$refs.fileTemp.click()
},

// 暂停或者继续
changeStauts(key) {
  const keyIndex = this.fileList.findIndex((item) => item.key == key);
  this.fileList[keyIndex].status = !this.fileList[keyIndex].status;
  if (this.fileList[keyIndex].status) {
    this.startUpload(key);
  }
},



}
});
</script>

<!-- <style scoped> -->
<style>
.upload-page{
          background-color: rgb(38,92,178);
          height: 100vh;
          width: 100vw;
          background-image:  url('~@/assets/2.png');
          background-size: cover;
          /* background-size: 100%; */
          margin: -8px;
        }

/* Add your component styles here */
.uploadinput{
  margin: 10px;
}

.process {
  margin: 10px;
}


/* 设置滑块的背景颜色 */
.el-slider__runway.disabled .el-slider__bar {
    background-color: #409EFF !important;
}

.upload-file-box {
    display: inline-block;
    position: relative;
    overflow: hidden;
    color: rgb(252, 113, 0);
    background-color: rgb(255, 255, 255);
}
 
.upload-file-btn {
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    outline: none;
    filter: alpha(opacity=0);
    -moz-opacity: 0;
    -khtml-opacity: 0;
    opacity: 0;
}

.upload-text{
  text-align: right;
  color: white;
}

</style>